package cn.fl.institution.controller;

import cmm.comm.facade.framework.api.ISysCdMapApiService;
import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.customer.service.ICstNpBscInfoService;
import cn.fl.customer.vo.CstNpBscInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.project.api.IPrjCstAccInfoApiService;
import cn.fl.project.condition.PrjCstAccInfoQueryCondition;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IPrjCstAccInfoService;
import cn.fl.project.service.IProjectApiService;
import cn.fl.system.service.ISysRegionService;
import cn.fl.system.vo.SysRegionVO;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;

/**
 * @Description: 项目基础信息表 控制层  宜宾银行
 */
@Controller
@RequestMapping("/institution/ybbank")
public class PrjBscInfoInsYbbankController {

	private static final Logger logger = LoggerFactory.getLogger(PrjBscInfoInsYbbankController.class);

    @Autowired
    private IPrjBscInfoService prjBscInfoService; // 项目基础信息表

	@Autowired
	private IPrjCstAccInfoApiService prjCstAccInfoApiService; // 项目客户账户信息表
	
	@Autowired
	private ICstBscInfoService cstBscInfoService; // 客户基础信息
	
	@Autowired
	private ICstNpBscInfoService cstNpBscInfoService; // 自然人信息
	@Autowired
	private ISysRegionService sysRegionService;//查询省市县
	@Autowired
	private IPrjCstAccInfoService prjCstAccInfoService;//项目客户基础信息表
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
    @Autowired
    private IProjectApiService projectApiService;
    /**
     * 代码映射服务
     */
    @Autowired
    private ISysCdMapApiService sysCdMapApiService;

    /**
     * 天津银行新增或修改项目客户账户信息及校验
     */
    @RequestMapping(value = "/ybbankAddOrModifyPrjAccInfo.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO ybbankAddOrModifyPrjAccInfo(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "ybbankAddOrModifyPrjAccInfo", "修改项目客户账户信息及校验"+ JSON.toJSONString(request.getParameterMap()), CurrentThreadContext.getCurrentUserName());
        String cstAccInfoId = request.getParameter("cstAccInfoId");//项目客户信息表id
        String insCode = request.getParameter("insCode");//机构code
        String prjId = request.getParameter("prjId");//项目id
        String cstId = request.getParameter("cstId");//客户id
        String cstNm = request.getParameter("cstNm");//客户姓名
        String bkNm = request.getParameter("bkNm");//银行名称
        String bkCd = request.getParameter("bkCd");//银行代码 -- 通用狮桥的数据字典表（CST0014） -- 资管特有的sys_cd_map_d表（M1041）
        String accNo = request.getParameter("accNo");//银行账号
        String mp = request.getParameter("mp");//手机号
        String domicileProvince = request.getParameter("rgnPrCd");//省
        String domicleCity = request.getParameter("rgnCyCd");//市
        String domicleCounty = request.getParameter("rgnCountyCd");//县
        String idAddr = request.getParameter("idAddr");//户籍所在地-详细地址
        String monthInc = request.getParameter("monthInc");//月收入
        String certValidSDt = request.getParameter("certValidSDt");//身份证有效起始时间
        String certValidEDt = request.getParameter("certValidEDt");//身份证有效结束时间
        String nation = request.getParameter("nation");//民族
        DataResultVO dataResultVO = null;
        try {
            if (StringUtils.isEmpty(prjId)) {
                BaseLogUtils.info(logger, "ybbankAddOrModifyPrjAccInfo", "项目id为空.", CurrentThreadContext.getCurrentUserName());
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "项目信息不完整!");
            }
            if (StringUtils.isEmpty(cstId)) {
                BaseLogUtils.info(logger, "ybbankAddOrModifyPrjAccInfo", "客户id为空", CurrentThreadContext.getCurrentUserName());
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "客户信息不完整!");
            }
            if (StringUtils.isBlank(cstNm)) {
                BaseLogUtils.info(logger, "ybbankAddOrModifyPrjAccInfo", "客户名称为空", CurrentThreadContext.getCurrentUserName());
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "客户信息不完整!");
            }
            if(StringUtils.isBlank(certValidSDt)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护证件有效起始日期!");
            }
            if(StringUtils.isBlank(certValidEDt)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护证件有效终止日期!");
            }
            if(StringUtils.isBlank(bkNm) || StringUtils.isBlank(bkCd)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护开户银行信息!");
            }
            if(StringUtils.isBlank(accNo)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护银行卡号!");
            }
            if(StringUtils.isBlank(mp)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护银行预留手机号!");
            }
            if(StringUtils.isBlank(monthInc)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护月收入!");
            }
            if(StringUtils.isBlank(nation)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护民族!");
            }
            if(StringUtils.isBlank(domicileProvince)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护户籍所在-省!");
            }
            if(StringUtils.isBlank(domicleCity)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维户籍所在-市!");
            }
            if(StringUtils.isBlank(idAddr)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维户籍所在-详细地址!");
            }
            //身份证地址拼接   户籍所在地 省+市+县 + 详细地址
            StringBuffer idAddrStringBuffer = new StringBuffer();
            if (StringUtils.isNotEmpty(domicileProvince)) {
                SysRegionVO sysRegionVO = this.sysRegionService.getRegionByRgnCd(domicileProvince);
                if(null != sysRegionVO && StringUtils.isNotEmpty(sysRegionVO.getRgnNm())){
                    idAddrStringBuffer.append(sysRegionVO.getRgnNm());
                }
            }
            if (StringUtils.isNotEmpty(domicleCity)) {
                SysRegionVO sysRegionVO = this.sysRegionService.getRegionByRgnCd(domicleCity);
                if(null != sysRegionVO && StringUtils.isNotEmpty(sysRegionVO.getRgnNm())){
                    idAddrStringBuffer.append(sysRegionVO.getRgnNm());
                }
            }
            if (StringUtils.isNotEmpty(domicleCounty)) {
                SysRegionVO sysRegionVO = this.sysRegionService.getRegionByRgnCd(domicleCounty);
                if(null != sysRegionVO && StringUtils.isNotEmpty(sysRegionVO.getRgnNm())){
                    idAddrStringBuffer.append(sysRegionVO.getRgnNm());
                }
            }
            idAddrStringBuffer.append(idAddr);
            idAddr = idAddrStringBuffer.toString();
            // 修改自然人月收入
            CstNpBscInfoVO cstNpBscInfoVO = this.cstNpBscInfoService.selectById(Long.valueOf(cstId));
            if(null != cstNpBscInfoVO) {
                Long mrIncMoney = DecimalUtils.convertYuanToFen(Double.valueOf(monthInc)); // 月收入转为分
                Double yrInc = DecimalUtils.mul(mrIncMoney.doubleValue(),12d); // 月收入转换年收入
                if (!Objects.equals(cstNpBscInfoVO.getYrInc().doubleValue(), yrInc) || !Objects.equals(cstNpBscInfoVO.getIdAddr(), idAddr)
                        || !Objects.equals(cstNpBscInfoVO.getDomicileProvince(), domicileProvince) || !Objects.equals(cstNpBscInfoVO.getDomicleCity(), domicleCity)
                        || !Objects.equals(cstNpBscInfoVO.getDomicleCounty(), domicleCounty) || !Objects.equals(cstNpBscInfoVO.getNation(), nation)) {
                    cstNpBscInfoVO.setYrInc(yrInc.longValue());
                    cstNpBscInfoVO.setIdAddr(idAddr);
                    cstNpBscInfoVO.setDomicileProvince(domicileProvince);
                    cstNpBscInfoVO.setDomicleCity(domicleCity);
                    cstNpBscInfoVO.setDomicleCounty(domicleCounty);
                    cstNpBscInfoVO.setNation(nation);
                    BaseLogUtils.info(logger, "ybbankAddOrModifyPrjAccInfo", "修改自然人信息 cstNpBscInfoVO"+ JSON.toJSONString(cstNpBscInfoVO), CurrentThreadContext.getCurrentUserName());
                    this.cstNpBscInfoService.modify(cstNpBscInfoVO);
                }
            }
            PrjCstAccInfoQueryCondition condition = new PrjCstAccInfoQueryCondition();
            if (StringUtils.isNotEmpty(cstAccInfoId)) {
                condition.setId(Long.valueOf(cstAccInfoId));
            }
            accNo = accNo.trim();
            condition.setPrjId(Long.valueOf(prjId));
            condition.setCstId(Long.valueOf(cstId));
            condition.setInsCode(insCode);
            condition.setCstNm(cstNm);
            condition.setAccNm(cstNm);
            condition.setBkCd(bkCd);
            condition.setBkNm(bkNm);
            condition.setAccNo(accNo);
            condition.setMp(mp);
            condition.setCertTypCd(DictionaryConstant.CODE_CERT_TYP_CD_0);
            condition.setCertValidSDt(certValidSDt);
            condition.setCertValidEDt(certValidEDt);
            dataResultVO = this.prjCstAccInfoService.modifyPrjAccInfo(condition);
            if(BaseConstant.IS_YESNO_YES == dataResultVO.getSuccess()){
                Map<String,String> resultMap = (Map<String, String>) dataResultVO.getData();
                String chkRstCd;
                String rstDesc;
                chkRstCd = resultMap.get("chkRstCd");
                rstDesc = resultMap.get("rstDesc");
                if (chkRstCd.equals("1")) {
                    dataResultVO.setSuccess(BaseConstant.IS_YESNO_YES);
                    dataResultVO.setInfo("四要素信息校验通过");
                } else {
                    dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
                    dataResultVO.setInfo(rstDesc);
                }
            }
        } catch (BaseException ex) {
            dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            dataResultVO.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "ybbankAddOrModifyPrjAccInfo", "新增或修改项目客户账户信息及校验,prjId:" + prjId + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }catch (Exception e){
            BaseLogUtils.info(logger, "ybbankAddOrModifyPrjAccInfo", "保存失败，系统异常",CurrentThreadContext.getCurrentUserName()+e.getMessage(),e);
            return new DataResultVO(BaseConstant.IS_YESNO_NO, "保存失败，系统异常");
        }
        BaseLogUtils.info(logger, "ybbankAddOrModifyPrjAccInfo", "新增或修改项目客户账户信息及校验返回=" + JSON.toJSONString(dataResultVO), CurrentThreadContext.getCurrentUserName());
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "ybbankAddOrModifyPrjAccInfo", "新增或修改项目客户账户信息及校验, PRJID:" + prjId, "-耗时:" + (endTm - startTm));
        return dataResultVO;
    }

}
